import { eq, desc, and } from 'drizzle-orm';
import { db } from '../database/connection.js';
import {
  conversations,
  messages,
  type Conversation,
  type NewConversation,
  type Message,
  type NewMessage,
} from '../database/schema.js';
import { v4 as uuidv4 } from 'uuid';

export class ConversationService {
  // 创建新对话
  static async create(
    characterId: string,
    title?: string
  ): Promise<Conversation> {
    const id = uuidv4();
    const newConversation: NewConversation = {
      id,
      characterId,
      title: title || `对话 ${new Date().toLocaleString()}`,
    };

    await db.insert(conversations).values(newConversation);
    const result = await db
      .select()
      .from(conversations)
      .where(eq(conversations.id, id));
    return result[0];
  }

  // 获取角色的所有对话
  static async findByCharacterId(characterId: string): Promise<Conversation[]> {
    return await db
      .select()
      .from(conversations)
      .where(
        and(
          eq(conversations.characterId, characterId),
          eq(conversations.isActive, true)
        )
      )
      .orderBy(desc(conversations.updatedAt));
  }

  // 根据ID获取对话
  static async findById(id: string): Promise<Conversation | null> {
    const result = await db
      .select()
      .from(conversations)
      .where(eq(conversations.id, id));
    return result[0] || null;
  }

  // 更新对话
  static async update(
    id: string,
    data: Partial<Omit<Conversation, 'id' | 'createdAt' | 'updatedAt'>>
  ): Promise<Conversation | null> {
    await db
      .update(conversations)
      .set({ ...data, updatedAt: new Date() })
      .where(eq(conversations.id, id));

    return await this.findById(id);
  }

  // 删除对话（软删除）
  static async delete(id: string): Promise<boolean> {
    const result = await db
      .update(conversations)
      .set({ isActive: false, updatedAt: new Date() })
      .where(eq(conversations.id, id));

    return result.length > 0;
  }
}

export class MessageService {
  // 添加消息
  static async create(
    conversationId: string,
    role: 'user' | 'assistant',
    content: string,
    metadata?: Record<string, any>
  ): Promise<Message> {
    const id = uuidv4();
    const newMessage: NewMessage = {
      id,
      conversationId,
      role,
      content,
      metadata,
    };

    await db.insert(messages).values(newMessage);

    // 更新对话的最后更新时间
    await db
      .update(conversations)
      .set({ updatedAt: new Date() })
      .where(eq(conversations.id, conversationId));

    const result = await db.select().from(messages).where(eq(messages.id, id));
    return result[0];
  }

  // 获取对话的所有消息
  static async findByConversationId(
    conversationId: string
  ): Promise<Message[]> {
    return await db
      .select()
      .from(messages)
      .where(eq(messages.conversationId, conversationId))
      .orderBy(messages.createdAt);
  }

  // 获取对话的最近N条消息
  static async findRecentMessages(
    conversationId: string,
    limit: number = 10
  ): Promise<Message[]> {
    return await db
      .select()
      .from(messages)
      .where(eq(messages.conversationId, conversationId))
      .orderBy(desc(messages.createdAt))
      .limit(limit);
  }

  // 删除消息
  static async delete(id: string): Promise<boolean> {
    const result = await db.delete(messages).where(eq(messages.id, id));

    return result.length > 0;
  }
}
